#
#    Copyright 2006 Andrew Wilkinson <aw@cs.york.ac.uk>.
#
#    This file is part of PyScobble (http://lastfm.indiegigs.co.uk/pyscrobble)
#
#    PyScobble is free software; you can redistribute it and/or modify
#    it under the terms of the GNU Lesser General Public License as published by
#    the Free Software Foundation; either version 2.1 of the License, or
#    (at your option) any later version.
#
#    PyScobble is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with PyScobble; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

import datetime

from scrobble import Artist, Track
from scrobble.database import getUserProfile, getUserFriends, getUserNeighbours
from scrobble.utils import *

## @class User
# A Last.fm User
#
# The username parameter must be passed, however the passwd field is optional and may be set at a later date
# using User.setPassword() if required.
#
# The password is currently only required when scrobbling tracks.
#
# @param username The username of the Last.fm to fetch.
# @param passwd The optional, unencoded password of the Last.fm user.
class User(object):
    def __init__(self, username, passwd=None):
        self.__username = username
        self.__passwd = passwd

        self.__profile = {"username": username}

    def scrobble(self, track, time=None):
        return scrobbleTrack(self, track, time)

    def getLink(self):
        return """<a href="http://www.last.fm/user/%s">%s</a>""" % (self.username, self.username)

    ## @var id
    # The user's id number.
    def __getId(self):
        return self.__getProfileInfo("id")
    id = property(__getId)
    def __getCluster(self):
        return self.__getProfileInfo("cluster")
    cluster = property(__getCluster)
    def __getUsername(self):
        return self.__getProfileInfo("username")
    username = property(__getUsername)
    def __getPasswd(self):
        return self.__passwd
    def __setPasswd(self, value):
        self.__passwd = value
    passwd = property(__getPasswd, __setPasswd)
    def __getUrl(self):
        return self.__getProfileInfo("url")
    url = property(__getUrl)
    def __getRealname(self):
        return self.__getProfileInfo("realname")
    realname = property(__getRealname)
    def __getMbox_sha1sum(self):
        return self.__getProfileInfo("mbox_sha1sum")
    mbox_sha1sum = property(__getMbox_sha1sum)
    def __getHomepage(self):
        return self.__getProfileInfo("homepage")
    homepage = property(__getHomepage)
    def __getRegistered(self):
        return self.__getProfileInfo("registered")
    registered = property(__getRegistered)
    def __getStatsreset(self):
        return self.__getProfileInfo("statsreset")
    statsreset = property(__getStatsreset)
    def __getAge(self):
        return self.__getProfileInfo("age")
    age = property(__getAge)
    def __getCountry(self):
        return self.__getProfileInfo("country")
    country = property(__getCountry)
    def __getPlaycount(self):
        return self.__getProfileInfo("playcount")
    playcount = property(__getPlaycount)
    def __getName(self):
        try:
            return self.__getProfileInfo("realname")
        except AttributeError:
            return self.__getProfileInfo("username")
    name = property(__getName)

    def __getFriends(self):
        if self.__profile.has_key("friends"):
            return self.__profile["friends"]

        friends = getUserFriends(self.__username)
        self.__profile["friends"] = [User(f) for f in friends]
        return self.__profile["friends"]
    friends = property(__getFriends)

    def __getNeighbours(self):
        if self.__profile.has_key("neighbours"):
            return self.__profile["neighbours"]

        neighbours = getUserNeighbours(self.__username)
        self.__profile["neighbours"] = [User(f) for f in neighbours]
        return self.__profile["neighbours"]
    neighbours = property(__getNeighbours)

    def __getRecentTracks(self):
        dom = getDom(audioscrobbler_webservices, "/1.0/user/%s/recenttracks.xml" % (self.username, ))

        r = []
        recenttracks = dom.getElementsByTagName("recenttracks")[0]
        for track in recenttracks.getElementsByTagName("track"):
            artist = getDomText(track.getElementsByTagName("artist")[0].childNodes)
            artist_mbid = track.getElementsByTagName("artist")[0].getAttribute("mbid")
            if artist_mbid == "":
                artist_mbid = None
            name = getDomText(track.getElementsByTagName("name")[0].childNodes)
            mbid = getDomText(track.getElementsByTagName("mbid")[0].childNodes)
            if mbid == "":
                mbid = None
            date = datetime.datetime.fromtimestamp(int(track.getElementsByTagName("date")[0].getAttribute("uts")))
            r.append((Track(artist=Artist(name=artist, mbid=artist_mbid), name=name, mbid=mbid), date))
        return r
    recenttracks = property(__getRecentTracks)

    def __getProfileInfo(self, attr):
        if not self.__profile.has_key(attr):
            self.__profile.update(getUserProfile(self.username))
        try:
            return self.__profile[attr]
        except KeyError:
            raise AttributeError, "No attribute %s" % (attr, )

    def __hash__(self):
        return hash(self.username)
    def __cmp__(self, other):
        return cmp(self.username, other.username)

    def __str__(self):
        return "%s" % (self.username, )
    def __repr__(self):
        return "<scrobble.User(%s)" % (repr(self.username), )

from scrobble.submit import scrobbleTrack
